<script setup lang="ts">
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import CodeEditor from '../components/CodeEditor.vue'
import httpClient from '../utils/http'
import { ElMessage } from 'element-plus'

const router = useRouter()

// 定义接口详情的类型
interface MockDetail {
  name: string
  url: string
  method: string
  status_code: number
  body: Record<string, any>
}

const mockForm = ref<MockDetail>({
  name: '',
  url: '/v1/mocs',
  method: 'GET',
  status_code: 200,
  body: {}
})

// 用于CodeEditor的响应式变量
const bodyString = ref('{"key":"value"}')

// 更新body值的函数
const updateBody = (value: string) => {
  try {
    mockForm.value.body = JSON.parse(value)
  } catch (error) {
    console.error('解析body失败:', error)
    // 如果解析失败，保持原有body不变，而不是设置为空对象
    // mockForm.value.body = {}
  }
}

// 监听mockForm.body的变化，仅在初始化时更新bodyString
watch(() => mockForm.value.body, (newVal, oldVal) => {
  // 只有当bodyString为空且有新的body值时才更新
  if (!bodyString.value && newVal) {
    try {
      bodyString.value = JSON.stringify(newVal, null, 2)
    } catch (error) {
      console.error('序列化body失败:', error)
      bodyString.value = '{}'
    }
  }
}, { immediate: true })

const methods = ref(['GET', 'POST', 'PUT', 'DELETE'])

const submitForm = async () => {
  // 显示确认对话框
  const confirmResult = window.confirm('确定要创建这个 Mock 接口吗?')
  if (!confirmResult) return

  // 提交表单逻辑
  console.log('创建 Mock 接口:', mockForm.value)
  
  // 确保body是对象而不是字符串
  let bodyData = mockForm.value.body;
  if (typeof bodyData === 'string') {
    try {
      bodyData = JSON.parse(bodyData);
    } catch (e) {
      console.error('body解析失败:', e);
    }
  }
  
  // 构造符合要求的数据格式
  const requestData = {
    name: mockForm.value.name,
    url: mockForm.value.url,
    headers: { "Content-Type": "application/json" },
    body: bodyData,
    status_code: mockForm.value.status_code,
    method: mockForm.value.method
  }
  
  // 打印实际发送的数据
  console.log('实际发送的requestData:', requestData)
  console.log('requestData.body类型:', typeof requestData.body)
  console.log('requestData.body内容:', requestData.body)
  
  try {
    // 发送创建请求到指定的URL
    const response = await httpClient.post('/v1/mocs', requestData)
    
    // 检查响应结构
    if (response?.data?.success) {
      console.log('创建成功:', response.data)
      ElMessage.success('创建接口成功')
      // 创建成功后跳转到列表页
      router.push('/')
    } else {
      // 处理失败响应
      const errorMsg = response?.data?.msg || '未知错误'
      const errorCode = response?.data?.code || response?.status || '未知状态码'
      console.error('创建失败:', response)
      alert(`创建失败: ${errorMsg} (错误代码: ${errorCode})`)
    }
  } catch (error: any) {
    // 处理网络错误或其他异常
    console.error('创建接口失败:', error)
    
    // 检查是否有响应数据（如500错误）
    if (error?.response) {
      const errorMsg = error.response?.data?.msg || error.response?.statusText || '服务器内部错误'
      const errorCode = error.response?.data?.code || error.response?.status || '未知状态码'
      alert(`创建接口失败: ${errorMsg} (错误代码: ${errorCode})`)
    } else {
      const errorMsg = error?.message || '网络错误或服务器无响应'
      alert(`创建接口失败: ${errorMsg}`)
    }
  }
}
</script>

<template>
  <div class="mock-create">
    <h1>创建 Mock 接口</h1>
    <el-form :model="mockForm" label-width="120px">
      <el-form-item label="接口名称">
        <el-input v-model="mockForm.name" />
      </el-form-item>
      <el-form-item label="URL">
        <el-input v-model="mockForm.url" />
      </el-form-item>
      <el-form-item label="方法">
        <el-select v-model="mockForm.method" placeholder="选择方法">
          <el-option
            v-for="method in methods"
            :key="method"
            :label="method"
            :value="method"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态码">
        <el-input v-model="mockForm.status_code" />
      </el-form-item>
      <!-- <el-form-item label="响应内容"> -->
      <strong>响应内容:</strong>
      <div class="response-content">
        <CodeEditor 
          v-model="bodyString"
          language="json" 
          style="height: 400px"
          @update:modelValue="updateBody"
        />
      </div>
      <!-- </el-form-item> -->
      <el-form-item>
        <el-button type="primary" @click="submitForm">创建</el-button>
        <el-button @click="router.push('/')">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
.mock-create {
  padding: 20px;
  max-width: 600px;
  margin: 0 auto;
}

.response-content {
  max-width: 100%;
  overflow-x: auto;
  text-align: left;
}

</style>